package bean;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

public class VolunteerBean {
    public ArrayList<Volunteer> adminArrayList;
    public HashMap<String,String> adminMap;
    public Connection connection;
    public PreparedStatement preparedStatement;
    public Statement statement;
    public ResultSet resultSet;

    public VolunteerBean() {
        this.adminArrayList = new ArrayList<>();
        this.adminMap = new HashMap<>();
    }

    public ArrayList<Volunteer> getVolunteerArrayList() {
        return adminArrayList;
    }

    public HashMap<String, String> getVolunteerMap() {
        return adminMap;
    }

    public void link() {
        try {
            Class.forName("org.hsqldb.jdbc.JDBCDriver");
            Connection connection=DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void loadVolunteer(){
        String sql="select * from Volunteer";
        try {
            statement=connection.createStatement();
            resultSet=statement.executeQuery(sql);
            while(resultSet.next()){
                Volunteer admin=new Volunteer(resultSet.getString(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4));
                adminArrayList.add(admin);
                adminMap.put(resultSet.getString(1),resultSet.getString(4));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public void insertVolunteer(Volunteer admin){
        adminArrayList.add(admin);
        adminMap.put(admin.getId(),admin.getPassword());
        String sql="insert into Volunteer values(?,?,?,?)";
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,admin.getId());
            preparedStatement.setString(2,admin.getName());
            preparedStatement.setString(3,admin.getSex());
            preparedStatement.setString(4,admin.getPassword());
            preparedStatement.execute();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    public Volunteer selectVolunteer(String id){
        String sql="select * from Volunteer where id=?";
        try {
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,id);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()){
                Volunteer admin = new Volunteer(resultSet.getString(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4));
                return admin;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }
}
